package org.example.uhy.domain.model.upgrade.execution.node;

import org.example.uhy.domain.model.member.MemberId;
import org.example.uhy.domain.model.upgrade.execution.UpgradeExecutionContext;

import java.util.List;

public class TradeCountRuleExecutionNode extends ConditionUpgradeExecutionNode<Integer> {
    public static final String TYPE = "TRADE_COUNT";

    public TradeCountRuleExecutionNode(Integer expectedValue) {
        super(expectedValue);
    }

    @Override
    public boolean match(UpgradeExecutionContext context) {
        Integer tradeCount = getAccumulationTradeCount(context);
        if (tradeCount == null || tradeCount == 0) {
            return false;
        }
        return tradeCount >= getExpectedValue();
    }

    private Integer getAccumulationTradeCount(UpgradeExecutionContext context) {
        if (context.hasCachedValue(TYPE)) {
            return context.getCachedValue(TYPE);
        }
        Integer accumulationTradeCount = 0;
        if (context.upgradeObject().isMember()) {
            accumulationTradeCount = context.tradeRepository().accumulationCountOfMember(context.upgradeObject().memberId());
        } else {
            List<MemberId> memberIds = membersOfContributor(context);
            if (memberIds != null && memberIds.size() > 0) {
                accumulationTradeCount = context.tradeRepository().accumulationCountOfMembers(memberIds);
            }
        }
        context.setCachedValue(TYPE, accumulationTradeCount);
        return accumulationTradeCount;
    }

    @Override
    public String getType() {
        return TYPE;
    }
}